package drds.global_transaction.resource_manager.sql_recognizer.impl;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr;
import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlDeleteStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;
import drds.global_transaction.resource_manager.ParameterObjectList;
import drds.global_transaction.resource_manager.sql_recognizer.SqlType;

import java.util.ArrayList;
import java.util.List;

public class DeleteSqlRecognizer extends AbstractSqlRecognizer implements drds.global_transaction.resource_manager.sql_recognizer.DeleteSqlRecognizer
{

	private final MySqlDeleteStatement mySqlDeleteStatement;

	public DeleteSqlRecognizer(String originalSql, SQLStatement mySqlDeleteStatement)
	{
		super(originalSql);
		this.mySqlDeleteStatement = (MySqlDeleteStatement) mySqlDeleteStatement;
	}

	@Override
	public SqlType getSqlType()
	{
		return SqlType.delete;
	}

	@Override
	public String getTableName()
	{
		StringBuilder sb = new StringBuilder();
		MySqlOutputVisitor mySqlOutputVisitor = new MySqlOutputVisitor(sb)
		{
			@Override
			public boolean visit(SQLExprTableSource sqlExprTableSource)
			{
				printTableSourceExpr(sqlExprTableSource.getExpr());
				return false;
			}
		};
		mySqlOutputVisitor.visit((SQLExprTableSource) mySqlDeleteStatement.getTableSource());
		return sb.toString();
	}

	@Override
	public String getTableSource()
	{
		StringBuilder sb = new StringBuilder();
		MySqlOutputVisitor mySqlOutputVisitor = new MySqlOutputVisitor(sb);
		mySqlOutputVisitor.visit((SQLExprTableSource) mySqlDeleteStatement.getTableSource());
		return sb.toString();
	}

	@Override
	public String getWhereCondition()
	{
		SQLExpr where = mySqlDeleteStatement.getWhere();
		if (where == null)
		{
			return "";
		}
		StringBuilder sb = new StringBuilder();
		MySqlOutputVisitor mySqlOutputVisitor = new MySqlOutputVisitor(sb);
		mySqlOutputVisitor.visit((SQLBinaryOpExpr) where);
		return sb.toString();
	}

	@Override
	public String getWhereCondition(final ParameterObjectList parameterObjectList, final ArrayList<Object> paramAppender)
	{
		SQLExpr where = mySqlDeleteStatement.getWhere();
		if (where == null)
		{
			return "";
		}
		StringBuilder sb = new StringBuilder();
		MySqlOutputVisitor mySqlOutputVisitor = new MySqlOutputVisitor(sb)
		{
			@Override
			public boolean visit(SQLVariantRefExpr sqlVariantRefExpr)
			{
				if ("?".equals(sqlVariantRefExpr.getName()))
				{
					List<Object> objectList = parameterObjectList.getParameterObjectList()[sqlVariantRefExpr.getIndex()];
					paramAppender.add(objectList.get(0));
				}
				return super.visit(sqlVariantRefExpr);
			}
		};
		mySqlOutputVisitor.visit((SQLBinaryOpExpr) where);
		return sb.toString();
	}

}
